/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-08-28 12:23:54
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-08-28 16:59:58
 * @FilePath: /Learn/pipe/testpipe.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<string> 
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024
using namespace std;
//child
void Writer(int wfd)
{
    string s="hello,I am child";
    pid_t self=getpid();
    int number=0;
    char buffer[NUM];
    while(1)
    {
        //构建发送字符串
        buffer[0]=0;//字符串清空
        //向buffer中输入内容
        //snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        //cout<<buffer<<endl;
        //写入/发送给父进程
        //write(wfd,buffer,strlen(buffer));
        char c='c';
        write(wfd,&c,1);
        sleep(1);
        cout<<++number<<endl;
    }
}
//father
void Reader(int rfd)
{
    char buffer[NUM];
    while(1)
    {
        sleep(50);
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;//当字符串使用
            cout<<"father get a message["<<getpid()<<"]:"<<buffer<<endl;
        }
        else if(n==0) 
        {
            cout<<"father read the file done"<<endl;
            break;
        }
        else break;
        //sleep(5);
    }
    exit(0);
}
int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0) return 1;
   // cout<<"pipefd[0]:"<<pipefd[0]<<",pipefd[1]:"<<pipefd[1]<<endl;
     pid_t id=fork();
     if(id<0) return 2;
     if(id==0)
     {
        //child
        close(pipefd[0]);//关闭读端
        //通信代码
        //..
        Writer(pipefd[1]);
        close(pipefd[1]);
     }
     //father
     close(pipefd[1]);//关闭写端
     //通信代码
     //..
     Reader(pipefd[0]);
     waitpid(id,nullptr,0);
     close(pipefd[0]);
     return 0;
}